//
//  UserAccountViewModel.swift
//  Weibo19
//
//  Created by 城 on 15/11/10.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import AFNetworking
class UserAccountViewModel: NSObject {

    var account :UserAccount?
    
    var userLogin:Bool{
    
        return false
    }
    
    override init() {
        account = UserAccount.loadAccount()
    }
    
    var token:String?{
        return account?.access_token
    }
    
    func loadAccessToken(code:String,finstang:(error:NSError?)->()){
        

        let afn = AFHTTPSessionManager()
        //        用于调用access_token，接口获取授权后的access token。
        //        expires_in 	string 	access_token的生命周期，单位是秒数。
        //        remind_in 	string 	access_token的生命周期（该参数即将废弃，开发者请使用expires_in）。
        //        uid 	string 	当前授权用户的UID。
        afn.responseSerializer.acceptableContentTypes?.insert("text/plain")//转换指示器
        let parameter = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]//必选的参数
        //token需要POST
        afn.POST("https://api.weibo.com/oauth2/access_token", parameters: parameter, success: { (_,result) -> Void in
            //判断是否有值
            
            //            let str = NSString(data: result as! NSData, encoding: NSUTF8StringEncoding)
            //            print(str)
            
            if let dict = result as? [String : AnyObject]{
                //取出token
                let user1 = UserAccount(dict: dict)
                //
                //                let access_token = user1.access_token!
                ////                //取出用户收起的UID
                //                let uid = user1.uid!
                
                self.loadUserInfo(user1, finstang: finstang)
            }
            
            //错误提示
            }) { (_, error) -> Void in
                print(error)
                
        }
    }
    
    private func loadUserInfo(user1:UserAccount,finstang:(error:NSError?)->()){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        //参数
        let parmater = ["access_token": user1.access_token!, "uid": user1.uid!]
        //实例化AFHTTPSessionManager
        let afn = AFHTTPSessionManager()
        
        afn.GET(urlString, parameters: parmater, success: { (_, make) -> Void in
            //判断是否有值,,这个方法内部一定是有值的
            if let dict = make as? [String: AnyObject]{
                
                user1.avatar_large = dict["avatar_large"] as? String
                user1.name = dict["name"] as? String
                print(user1)
                user1.saveObject()
                finstang(error: nil)

            
            }
            
            }) { (_, error) -> Void in
                finstang(error: error)

                print(error)
        }
        
        

        
        
    }
    
}
